<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        v-model.trim="kw"
        v-focus
        placeholder="请输入搜索关键词"
        background="#333"
        shape="round"
        @input="inputFn"
        @search="searchFn"
      />
    </div>
    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="suggestList[0]">
      <div
        class="sugg-item"
        v-for="(item, index) in suggestList"
        :key="index"
        v-html="lightFn(item, kw)"
        @click="suggestClickFn(item)"
      ></div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-if="!kw.length">
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="history = []" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          v-for="(item, index) in history"
          :key="index"
          @click="historyClickFn(item)"
          >{{ item }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { searchSuggestionAPI } from '@/api'
import { getStorage, setStorage } from '@/utils/storage'
export default {
  name: 'mySearch',
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null, // 防抖的定时器
      suggestList: [], // 建议关键字列表
      history: JSON.parse(getStorage('history')) || [] // 搜索历史
    }
  },
  methods: {
    // 输入框内容改变时触发的方法
    inputFn () {
      clearTimeout(this.timer)
      this.suggestList = []
      if (this.kw.length > 0) {
        // 防抖：延时执行代码，事件再次触发时，清除上一个定时器
        this.timer = setTimeout(async () => {
          if (this.kw.length === 0) return false
          const { data: res } = await searchSuggestionAPI(this.kw)
          this.suggestList = res.data.options
        }, 300)
      }
    },
    // 处理字符串关键字高亮的方法
    lightFn (originStr, target) {
      // originStr：原来的字符串
      // target：关键字
      const reg = new RegExp(target, 'ig')
      return originStr.replaceAll(reg, (match) => {
        return `<span style="color: red">${match}</span>`
      })
    },
    // 跳转路由至搜索结果页
    moveFn (str) {
      setTimeout(() => {
        this.$router.push('/searchResult/' + str)
      }, 0)
    },
    // 搜索关键字触发的方法
    searchFn () {
      if (!this.kw.length) return
      this.history.push(this.kw)
      this.moveFn(this.kw)
    },
    // 联想菜单的点击事件
    suggestClickFn (str) {
      this.history.push(str)
      this.moveFn(str)
    },
    // 历史搜索的点击事件
    historyClickFn (str) {
      this.moveFn(str)
    }
  },
  watch: {
    history: {
      deep: true,
      handler () {
        setStorage('history', JSON.stringify(Array.from(new Set(this.history))))
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #333;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
